from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from user.models import User
from .article_serializers import *
from .paginators import MyPage



# 关键字搜索文章
class QueryListView(ListAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializerList
    pagination_class = MyPage
    def get_queryset(self):
        text = self.request.query_params.get('text')
        atr = Article.objects.filter(title = text)
        return atr


#频道列表
class ChannelView(ModelViewSet):
    queryset = Channel.objects.all()
    serializer_class = ChannelSerializer
    pagination_class = MyPage


#文章列表
class ArticleView(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializerList
    pagination_class = MyPage

    def create(self, request, *args, **kwargs):

        try:
            user = self.request.user
        except Exception as e:
            user = None

        if user is not None and user.is_authenticated:
            user_data =request.data
            user_data['user']=user.id
            serializer=ArticleSerializerForCreate(data=user_data)
            serializer.is_valid(raise_exception=True)
            article =serializer.save()

            return Response({'success':True,
                                    'message':'发表成功',
                                   'articleid':article.id})
        else:
            return Response({'success':False,
                                'message':'未登录'},status=400
                                )



    # @action(methods=['get'], detail=True, url_path="channel")
    # def get_article_channel(self, request, pk):
    #     if pk == "-1":
    #         articles = self.get_queryset()
    #     else:
    #         channel = Channel.objects.get(id=pk)
    #         articles = self.get_queryset().filter(channel=channel)
    #
    #     page = self.paginate_queryset(articles)
    #     s = ArticleSerializerList(page, many=True)
    #     return self.get_paginated_response(s.data)


class LabelListAPIView(ListAPIView):
    queryset = Label.objects.all()
    serializer_class = LabelSerializer